package org.jeecg.modules.cascv.image.service.merge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
@Service
@Slf4j
public class ShengmingguiService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "6D5DH_41H,6D7DH_41H,6D1DH_42H,6D1DH_47H,6D1DH_48H,6D3DH_42H";
    }

    //ffd8 开头 ffd9结束
    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {

        JSONObject content = jsonObject.getJSONObject("Content");


        //打印报错不连续的包序号
        String packageNum = content.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }


            String hexStr = content.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
            //  hexStr = hexStr.substring(7, hexStr.length() - 10);
            hexStr = hexStr.split(";")[1];
            hexStr = hexStr.substring(2).trim();
            String startEndFlag = content.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
            startEndFlag = startEndFlag.split(";")[0];


            if (StringUtils.isBlank(hexStr)) return Result.error("图像数据为空！");
            StringBuilder imageData = LaptopConstant.imageData.get(key);

            if (hexStr.startsWith("FFD8")) {
                imageData = new StringBuilder();
                LaptopConstant.imageData.put(key, imageData);
                imageData.append(hexStr);
            } else if (imageData != null && hexStr.contains("FFD9")||LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag) ) {
                int endIndex = hexStr.indexOf("FFD9");
                String substring = hexStr.substring(0, endIndex + 4);
                imageData.append(substring);
//            int fill = 2006 - (imageData.length() / 2);
//           if (fill > 0) {
//               for (int i = 0; i < fill; i++) {
//                   imageData.append("ba");
//               }
//           }

                int length = imageData.toString().toCharArray().length;
                String imgHexStr = imageData.toString();
                // if (!((length & 1) != 0)) { //最后可能有异常数据 导致长度是奇数报错，这里判断一下
                CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                    long start = System.currentTimeMillis();
                    //十六进制字符串转换为字节数组
                    byte[] result = HexUtil.decodeHex(imgHexStr);
                    //随机字符
                    String idStr = IdWorker.getIdStr();
                    FileUtil.touch("/data/images/" + idStr + ".jpeg");

                    //生成图片
                    try {
                        FileUtil.writeBytes(result, "/data/images/" + idStr + ".jpeg");
                    } catch (Exception e) {
                        log.error("生命柜图片生成失败1," + e);
                        e.printStackTrace();

                    }
                    BufferedImage bi = null;
                    try {

                        bi = ImageIO.read(new File("/data/images/" + idStr + ".jpeg"));
                        BufferedImage bufferedImage = rotate90SX(bi);
                        ImageIO.write(bufferedImage, "jpeg", new File("/data/images/" + idStr + ".jpeg"));
                        int width = bi.getWidth();
                        int height = bi.getHeight();
                    } catch (Exception e) {
                        log.error("生命柜图片生成失败2", e);
                        e.printStackTrace();

                    }
                    String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".jpeg";
                    System.out.println("imageUrl = " + imageUrl);
                    content.put("imageUrl", imageUrl);
                    content.put("idsName", idsName);
                    String secondStr = jsonObject.getString("second");
                    long second = Long.parseLong(secondStr);
                    String subSecondStr = jsonObject.getString("subsecond");
                    secondStr = LaptopUtil.toDayHoursMinSec(second);

                    String[] split2 = secondStr.split(":");
                    content.put("ts", split2[0] + "天" + split2[1] + "时" + split2[2] + "分" + split2[3] + "秒" + subSecondStr + "微秒");
                    content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                    content.put("key", key);
                    log.info("生命生态实验柜"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                    return content;
                }, taskExecutePool.threadPoolTaskExecutor2());
                LaptopConstant.imageFutureList.add(future);

            } else if (imageData != null) {
                imageData.append(hexStr);
            }
            return null;
        }


        public static void main (String[]args){
            System.load("D:/disk1/libjpeg-9.dll");
            System.load("D:/disk1/libpng-3.dll");
            System.load("D:/disk1/NativeImageIOJNI.dll");
            //D:\pc_workspace\shengmingui2\    D:\图像数据\生命柜
            List<String> strings = FileUtil.readUtf8Lines("E:\\图像数据\\cut\\生命生态\\T20221214195358_0001_0063_F1_00_6DCD_2024_0042_42_6D1D_000000000.txt");
            ShengmingguiService shengmingguiService = new ShengmingguiService();

            for (String string : strings) {
                //将str转化为相应的JSONObject对象
                JSONObject jsonObject = JSONObject.parseObject(string);

                shengmingguiService.merge(jsonObject, "6D1DH_42H", "6D1DH_42H");
            }

        }

        public static BufferedImage rotate90SX (BufferedImage bi){
            int width = bi.getWidth();
            int height = bi.getHeight();
            BufferedImage biFlip = new BufferedImage(height, width, bi.getType());
            for (int i = 0; i < width; i++)
                for (int j = 0; j < height; j++)
                    biFlip.setRGB(height - 1 - j, i, bi.getRGB(i, j));

            return biFlip;
        }
    }
